﻿@page "/bbs/post/{id}"
@inherits BaseComponent

<PageTitle>@model?.Title - @AppConfig.AppTitle</PageTitle>

<div class="container cl-container cl-post">
    <div>
        <CmsCard>
            <HeadTemplate>
                <CmsTitle Icon="far fa-file" Title="问题详情" />
                <UPostCount Post="model" />
            </HeadTemplate>
            <ChildContent>
                <div class="title">@model?.Title</div>
                <UPostInfo Model="model" />
                <div class="button">
                    <AntButton Name="返回" Type="default" OnClick="location='./bbs';" />
                </div>
            </ChildContent>
        </CmsCard>
        <div style="height:20px;"></div>
        <CmsCard Title="回复列表">
            @if (CurrentUser != null)
            {
                <div style="display:grid;grid-template-columns:40px auto;">
                    <div>
                        <AntAvatar Src="@CurrentUser?.AvatarUrl" />
                    </div>
                    <div>
                        @if (!string.IsNullOrWhiteSpace(errorMessage))
                        {
                            <AntAlert Type="error">@errorMessage</AntAlert>
                        }
                        <AntForm Id="@formId">
                            <CmsMarkdown Id="@nameof(ReplyFormInfo.Content)" Value="@reply?.Content" AutoFocus="autoFocus" Height="200" Placeholder="在这里输入回答内容" />
                            <div class="button">
                                <AntButton Name="回复" OnClick="@($"return AntBlazor.validate('{formId}');")" />
                            </div>
                        </AntForm>
                    </div>
                </div>
            }
            @if (model?.Replies == null || model?.Replies.Count == 0)
            {
                <AntEmpty />
            }
            else
            {
                foreach (var item in model?.Replies)
                {
                    <UReplyItem Item="item" />
                }
            }
        </CmsCard>
    </div>
    <div>
        <UUserBox Service="Service" />
        <div style="height:20px;"></div>
        <UPostRank Service="Service" />
    </div>
</div>

@code {
    private ISiteService Service;
    private PostDetailInfo model;
    private bool autoFocus = false;
    private string formId = "reply-form";
    private string errorMessage = "";
    private ReplyFormInfo reply = new();

    protected override async Task OnInitAsync()
    {
        await base.OnInitAsync();
        Service = await CreateServiceAsync<ISiteService>();
        if (Context.Request.IsHandler(formId))
        {
            autoFocus = true;
            reply = Context.Request.GetModel<ReplyFormInfo>();
            reply.BizId = Id;
            var result = await Service.SaveReplyAsync(reply);
            if (!result.IsValid)
                errorMessage = result.Message;
        }
        model = await Service.GetPostAsync(ContentType.Interact, Id);
    }
}